package com.jplus._20Dubbo.config;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.jplus.core.anno.boot.Component;
import com.jplus.core.anno.com.Autowired;
import com.jplus.core.anno.com.Scope.EScope;
import com.jplus.core.core.ApplicationContext;
import com.jplus.core.core.beans.BeanKey;

@Component
public class DubboHandle {

	private @Autowired ApplicationContext applicationContext;
	private @Autowired ApplicationConfig application;
	private @Autowired RegistryConfig registry;
	private @Autowired ProtocolConfig protocol;

	private String version = "1.0.0";

	// 2.常规API配置：service
	public <T> ServiceConfig<T> buildSrviceConfig(Class<T> iface, T impl) {
		// 注意：ServiceConfig为重对象，内部封装了与注册中心的连接，以及开启服务端口
		// 服务提供者暴露服务配置
		ServiceConfig<T> service = new ServiceConfig<>();
		service.setApplication(application);
		service.setRegistry(registry); // 多个注册中心可以用setRegistries()
		service.setProtocol(protocol); // 多个协议可以用setProtocols()
		service.setInterface(iface);
		service.setRef(impl);
		service.setVersion(version);
		service.export(); // 发布服务
		return service;
	}

	// 2.常规API配置:reference
	public <T> ReferenceConfig<T> buildReferenceConfig(Class<T> iface) {
		// 引用远程服务
		// 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
		ReferenceConfig<T> reference = new ReferenceConfig<T>();
		reference.setApplication(application);
		reference.setRegistry(registry); // 多个注册中心可以用setRegistries()
		reference.setInterface(iface);
		reference.setVersion(version);

		// 将Dubbo代理客户端，加入 Jplus的bean容器
		applicationContext.getBeanFactory().buildBean(new BeanKey(iface), reference.get(), EScope.SINGLETON);

		return reference;
	}
}
